<template>
    <div class="login-container">
        <el-card class="login-card">
            <template #header>
                <h2 class="login-title">登录</h2>
            </template>

            <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
                <el-form-item prop="username">
                    <el-input v-model="loginForm.username" placeholder="用户名" prefix-icon="User" />
                </el-form-item>

                <el-form-item prop="password">
                    <el-input v-model="loginForm.password" type="password" placeholder="密码" prefix-icon="Lock"
                        show-password />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" class="login-button" :loading="loading" @click="handleLogin">
                        登录
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const store = useStore()
const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)

const loginForm = reactive({
    username: '',
    password: ''
})

const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ]
}

const handleLogin = () => {
    loginFormRef.value.validate(async (valid) => {
        if (!valid) return

        // 假登录逻辑
        if (loginForm.username === 'admin' && loginForm.password === '123456') {
            // 管理员登录
            const mockUserInfo = {
                userInfo: {
                    role: 'teacher',
                    name: '管理员'
                }
            }
            await store.dispatch('login', mockUserInfo)
            ElMessage.success('管理员登录成功')
            router.push('/students')
        } else if (loginForm.username === 'test' && loginForm.password === '123456') {
            // 学生登录
            const mockUserInfo = {
                userInfo: {
                    role: 'student',
                    name: '测试学生'
                }
            }
            await store.dispatch('login', mockUserInfo)
            ElMessage.success('学生登录成功')
            router.push('/my-rewards')
        } else {
            ElMessage.error('账号或密码错误')
        }
    })
}
</script>

<style scoped>
.login-container {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f5f7fa;
}

.login-card {
    width: 400px;
}

.login-title {
    text-align: center;
    margin: 0;
    color: #409EFF;
}

.login-button {
    width: 100%;
}
</style>